package com.peter.viewpager2;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import java.util.ArrayList;
import java.util.List;


public class DemoFragmentAdapter extends FragmentStateAdapter {

    private List<Fragment> mFragmentList;

    DemoFragmentAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
        mFragmentList = new ArrayList<>();
    }

    public DemoFragmentAdapter(@NonNull Fragment fragment) {
        super(fragment);
        mFragmentList = new ArrayList<>();
    }

    public DemoFragmentAdapter(@NonNull FragmentManager fragmentManager, @NonNull Lifecycle lifecycle) {
        super(fragmentManager, lifecycle);
        mFragmentList = new ArrayList<>();
    }

    //添加一个Fragment
    void addFragment(Fragment fragment){
        mFragmentList.add(fragment);
        notifyDataSetChanged();
    }
    //删除一个Fragment
    void removeFragment(){
        if (mFragmentList.size() > 0 ){
            mFragmentList.remove(mFragmentList.size() - 1);
            notifyDataSetChanged();
        }
    }

    @NonNull @Override public Fragment createFragment(int position) {
        return mFragmentList.get(position);
    }

    @Override public int getItemCount() {
        return mFragmentList.size();
    }
}

